﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Diagnostics;

namespace Fitness_club
{
    public partial class AttendanceEntering : Form
    {
        static string connection = ConfigurationManager.AppSettings["ConStr"].ToString();
        SqlConnection con = new SqlConnection(connection);

        Fitness_club.helper get = new Fitness_club.helper();

        public AttendanceEntering()
        {
            InitializeComponent();
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.txtMemberID.Text.Length == 0)
                {
                    MessageBox.Show("Member ID should not be empty!!!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtMemberID.Focus();
                    return;
                }

                //Stopwatch watch = Stopwatch.StartNew();
                
                //check the foreign key id is already exists or nots
                SqlCommand cmd1 = new SqlCommand("select COUNT(*)FROM member WHERE id=@id"); //IS NULL");
                cmd1.Connection = con;
                cmd1.Parameters.Add("@id", SqlDbType.BigInt).Value = txtMemberID.Text;               

                con.Open();
                int OBJ = Convert.ToInt32(cmd1.ExecuteScalar());

                //check if the id and date is already exists or not
                DateTime DDate = DateTime.Today;
                string memDate = DDate.ToString("d");
                SqlCommand validateDate = new SqlCommand("select COUNT(*) as total from Attendance where MemberId = @memberid and indate = Convert(date, GETDATE())");
                validateDate.Connection = con;
                validateDate.Parameters.Add("@memberid", SqlDbType.BigInt).Value = txtMemberID.Text;
                validateDate.Parameters.Add("@indate", SqlDbType.Date).Value = memDate;
                SqlDataAdapter adapt = new SqlDataAdapter(validateDate);
                DataTable dt = new DataTable();
                adapt.Fill(dt);
                int result = 0;
                result = Convert.ToInt32(dt.Rows[0]["total"].ToString());

                if (OBJ > 0)
                {
                    if (result == 0)
                    {

                        DateTime theDate = DateTime.Today;
                        string customDate = theDate.ToString("d");

                        DateTime time = DateTime.Now;
                        string currentTime = time.ToString("hh:mm:ss");

                        string str = string.Empty;
                        str = "insert into Attendance(MemberId,indate,intime)values(@memberid,@indate,@intime)";

                        SqlCommand cmd = new SqlCommand();
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = str;

                        cmd.Parameters.Add("@memberid", SqlDbType.Int).Value = txtMemberID.Text;
                        cmd.Parameters.Add("@indate", SqlDbType.Date).Value = customDate;
                        cmd.Parameters.Add("@intime", SqlDbType.Time).Value = currentTime;

                        get.SqlCmd_Exec(cmd);
                        con.Close();
                        displayAttendanceSuccess(Int32.Parse(txtMemberID.Text));
                        
                    }
                    else
                    {
                        MessageBox.Show("This member already have attendance entry!!!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    MessageBox.Show("Invalid member id !!!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }                    
               // MessageBox.Show(watch.Elapsed.TotalMilliseconds.ToString());
               
            catch (Exception ex)
            {
                //MessageBox.Show("", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                AttendanceLanding land = new AttendanceLanding();
                land.Show();
                this.Dispose();
            }
        }

        private void displayAttendanceSuccess(int memId)
        {
            try
            {
                String message = "Intime saved successfully! ";
                SqlCommand command = new SqlCommand("SELECT * from member where mem_id=" + memId, con);

                // SqlCommand command = new SqlCommand("SELECT * from fees_transaction where id", con);
                con.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        String userName = reader["firstname"].ToString();
                        String dueDate = reader["due_date"].ToString();
                        DateTime dueDateTime = DateTime.Parse(dueDate);
                        dueDate = dueDateTime.ToString(Constants.DATE_FORMAT);
                        if (userName != null && dueDate != null)
                        {
                            message = "Hi " + userName + " ! attendace saved successfully \nyour next due date is " + dueDate;
                        }
                    }
                }
                con.Close();

                string title = "Attendance";
                MessageBox.Show(message, title);
                this.Close();
            }
            catch (Exception exc)
            {
                MessageBox.Show("InTime Attendance is not saved successfully, Try Again", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //private bool Datevalidation()
        //{
        //    bool flag = true;

        //    //SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConStr"]);
        //    string strSql = string.Empty;
        //    strSql = "select id, MemberId, intime, outtime from [Attendance] where intime ='" + txtINTIME.Text.Trim() + "'";
        //    SqlCommand cmd = new SqlCommand(strSql, con);
        //    SqlDataAdapter sda = new SqlDataAdapter(cmd);
        //    DataTable dtUsers = new DataTable();
        //    sda.Fill(dtUsers);
        //    if (dtUsers.Rows.Count > 0)
        //    {
        //        for (int cnt = 0; cnt < dtUsers.Rows.Count; cnt++)
        //        {
        //            if (dtUsers.Rows[cnt]["intime"].ToString().Trim() == txtINTIME.Text.Trim())
        //            {
        //                flag = false;
        //                break;
        //            }
        //        }
        //    }

        //    return flag;
        //}

        private void AttendanceEntering_Load(object sender, EventArgs e)
        {

        }

        private void txtMemberID_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
        }

        //private void buttonINTIME_Click(object sender, EventArgs e)
        //{
        //    //txtINTIME.Text = DateTime.Now.ToString();//"hh:mm:ss tt");
        //    txtINTIME.Text = DateTime.Now.ToString("yyyy/MM/dd");
        //}


        //private void fetchMemberById(int id)
        //{
        //    try
        //    {
        //        SqlCommand sqlCommand = new SqlCommand("select * from Attendance where id=" + id, con);
        //        con.Open();
        //        SqlDataReader reader = sqlCommand.ExecuteReader();

        //        if (reader != null)
        //        {
        //            while (reader.Read())
        //            {
        //                txtFirstName.Text = reader["firstname"].ToString();
        //                txtMemberID.Text = reader["MemberId"];
        //                txtINTIME.Text = reader["intime"];   
        //            }
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //    }
        //    finally
        //    {
        //        con.Close();
        //    }
        //}
    }
}
